const config = require("../config.js");
const {mysqlService} = require("./mysqlService.js");
let normalResult = require("../normalResult.js")

const baseModel = {
    getAll: async (sql) => {
        let result = JSON.parse(normalResult)
        try {
            result.data = await mysqlService(sql, []);
            return result
        } catch (error) {
            result = Object.assign(result, config.result.error)
            return result
        }
    },

    // sql示例：select id, name, price from mo_goods
    getDataById: async (sql, id) => {
        let result = JSON.parse(normalResult)
        sql += ` where id = ${id}`
        try {
            let r = await mysqlService(sql, []);
            if (r.length) {
                result.data = r[0];
                return result;
            } else {
                result = Object.assign(result, config.result.notData)
                return result;
            }
        } catch (error) {
            result = Object.assign(result, config.result.sqlError)
            return result
        }
    },

    add: async (table, params) => {
        let result = JSON.parse(normalResult)
        if (params.id) delete params.id;
        let sql = `insert into ${table} (`;
        sql += Object.keys(params).join(",");
        sql += `) values (`;
        sql += Object.values(params).map(item => {
            return `'${item}'`
        }).join(",");
        sql += ')'
        try {
            let res = await mysqlService(sql, []);
            result.data = res.insertId;
            return result;
        } catch (error) {
            //TODO handle error
            result = Object.assign(result, config.result.error)
            return result
        }
    },

    updateById: async (table, params) => {
        let result = JSON.parse(normalResult)
        let data = {}
        let id = 0
        if (params.id) {
            id = params.id
            delete params.id
            data = Object.assign({}, params)
        } else {
            result = config.result.missingPrimaryError;
            return result
        }
        let sql = `update ${table}`
        sql += ' set '
        for (let key in data) {
            sql += `${key} = '${data[key]}',`
        }
        sql = sql.substring(0, sql.length - 1);
        sql += ` where id = ${id}`
        try {
            await mysqlService(sql, []);
            result.data = id;
            return result;
        } catch (error) {
            //TODO handle error
            result = Object.assign(result, config.result.operationError)
            return result
        }
    },

    // let totalSql = "SELECT COUNT(*) AS total FROM mo_goods";
    // let sql = 'select id, name, price from mo_goods';
    getPagination: async (sql, totalSql, page, size) => {
        let result = JSON.parse(normalResult)
        page = parseInt(page) || 1;
        size = parseInt(size) || 10;
        const offset = (page - 1) * size;
        try {
            sql = `${sql} limit ?, ?`;
            result.data = await mysqlService(sql, [offset, size]);
            if (totalSql) {
                const t = await mysqlService(totalSql, []);
                result.total = t[0].total || 0;
            }
            return result
        } catch (error) {
            result = Object.assign(result, config.result.operationError)
            return result
        }
    },

    realDelById: async (table, id) => {
        let result = JSON.parse(normalResult)
        let sql = 'delete from ' + table + ' where id = ' + id;
        try {
            let res = await mysqlService(sql, []);
            if (res.affectedRows) {
                result.msg = '删除成功'
                result.data = id
                return result
            } else {
                result = Object.assign(result, config.result.notData)
                return result
            }
        } catch (error) {
            result = Object.assign(result, config.result.error)
            return result
        }
    },

};

module.exports = {
    baseModel: baseModel
}
